<?php

namespace app\controller;

use app\BaseController;
use app\model\Project;
use app\model\User;
use app\utils\QC;
use think\App;
use think\facade\Cache;
use think\facade\View;
use think\facade\Db as db;
use think\Model;
use think\Request;
use function Sodium\add;


class AuthController extends BaseController
{

    public function __construct(App $app)
    {
        parent::__construct($app);
        echo '123';

    }


    public function qq_login()
    {
        $qc = new QC();
        $url = $qc->GetAuthorizeUrl();
        return redirect($url);
    }


    public function qq_callback()
    {
        $qc = new QC();
        $code = \request()->param('code');
        $token_info = $qc->GetAccessToken($code);
        $token = $token_info['access_token'];

        $openid = $qc->GetOpenid($token);

        $qquser = $qc->GetUser($token, $openid);
        //var_dump($qquser);

        $userModel = new User();


        $user = $userModel->where('qq_openid',$openid)->find();
        if ($user == null) {
            //echo '<html>此QQ未绑定账号, <a href="/register">去注册</a> <a href="/login">去登录</a> </html>';
            $id = Db::table('user')->insert([
                //'username' => '',
                //'password' => '',
                'nickname' => $qquser['nickname'],
                'email' => '',
                //'salt' => '',
                'qq_openid' => $openid,
                'avatar' => $qquser['figureurl_qq_1'],
                'phone' => '',

            ],true);

            $user = $userModel->where('qq_openid',$openid)->find();

        }
        //echo $user;

        //如果查询到user信息
        //$token = uuid();
        //$redis = Cache::store('redis');
        session('login_user',$user);

        //跳转到最后标记的页面
        $last_uri = session('last_uri');
        if ($last_uri===null){
            return redirect('/');
        }
        return redirect($last_uri);

    }



}
